package com.yihu.wlyy.service.app.scheduling;

import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.WlyyDoctorWorkTime;
import com.yihu.wlyy.entity.WlyyDoctorWorkWeek;
import com.yihu.wlyy.repository.DoctorDao;
import com.yihu.wlyy.repository.DoctorWorkTimeDao;
import com.yihu.wlyy.repository.DoctorWorkWeekDao;
import com.yihu.wlyy.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;

/**
 * 医生工作排班
 *
 * Created by lyr on 2016/08/19.
 */
@Service
@Transactional
public class DoctorWorkTimeService extends BaseService {

    @Autowired
    private DoctorWorkTimeDao doctorWorkTimeDao;
    @Autowired
    private DoctorWorkWeekDao doctorWorkWeekDao;
    @Autowired
    private DoctorDao doctorDao;

    /**
     * 查询医生工作时间列表
     *
     * @param doctor 医生标识
     * @return
     */
    public JSONObject findDoctorWorkTime(String doctor){
        JSONObject result = new JSONObject();
        WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        List<WlyyDoctorWorkWeek> workWeekList = doctorWorkWeekDao.findDoctorWorkWeeks(doctor);

        result.put("workTime",workTime != null ? new JSONObject(workTime): "");
        result.put("workWeeks",workWeekList != null ? new JSONArray(workWeekList): "");

        return result;
    }

    /**
     * 查询医生某天工作时间
     *
     * @param doctor 医生标识
     * @param week 某天
     * @return
     */
    public JSONObject findDoctorWeekWorkTime(String doctor,String week){
        JSONObject result = new JSONObject();
        WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        WlyyDoctorWorkWeek workWeek = doctorWorkWeekDao.findDoctorWorkWeek(doctor,week);

        result.put("workTime",workTime != null ? new JSONObject(workTime): "");
        result.put("workWeek",workWeek != null ? new JSONObject(workWeek) : "");

        return result;
    }

    /**
     * 查询医生某天工作时间
     *
     * @param doctor 医生标识
     * @param week 某天
     * @return
     */
    public Map<String,Object> findDoctorWeekWork(String doctor,String week){
        Map<String,Object> map = new HashMap<>();
        WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        WlyyDoctorWorkWeek workWeek = doctorWorkWeekDao.findDoctorWorkWeek(doctor,week);

        map.put("workTime",workTime);
        map.put("workWeek",workWeek);

        return map;
    }

    /**
     * 保存医生工作排班
     *
     * @param doctor 医生
     * @param workScheduling 排班配置
     * @return
     */
    public boolean saveDoctorWorkTime(String doctor,JSONObject workScheduling) throws Exception {

        JSONObject workTime = workScheduling.has("workTime") ? workScheduling.getJSONObject("workTime") : null;
        JSONArray workTWeeks = workScheduling.has("workWeeks") ? workScheduling.getJSONArray("workWeeks") : null;

        WlyyDoctorWorkTime doctorWorkTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        Doctor doc = doctorDao.findByCode(doctor);

        if(StringUtils.isEmpty(doctor) || doc == null){
            throw new Exception("找不到对应医生!");
        }
        if(workTime == null){
            throw new Exception("工作时间段不能为空!");
        }

        if(doctorWorkTime == null){
            doctorWorkTime = new WlyyDoctorWorkTime();
            doctorWorkTime.setReceiveConsult("1");
        }

        // 医生
        doctorWorkTime.setDoctor(doctor);
        // 医生姓名
        doctorWorkTime.setDoctorName(doc.getName());
        // 上午开始时间
        doctorWorkTime.setMorningBegin(workTime.getString("morningBegin"));
        // 上午结束时间
        doctorWorkTime.setMorningEnd(workTime.getString("morningEnd"));
        // 下午开始时间
        doctorWorkTime.setAfternoonBegin(workTime.getString("afternoonBegin"));
        // 下午结束时间
        doctorWorkTime.setAfternoonEnd(workTime.getString("afternoonEnd"));
        // 晚上开始时间
        doctorWorkTime.setNightBegin(workTime.getString("nightBegin"));
        // 晚上结束时间
        doctorWorkTime.setNightEnd(workTime.getString("nightEnd"));
        // 更新时间
        doctorWorkTime.setCzrq(new Date());

        doctorWorkTimeDao.save(doctorWorkTime);
        doctorWorkWeekDao.deleteByDoctor(doctor);

        // 排班保存
        if(workTWeeks != null){
            List<WlyyDoctorWorkWeek> weeks = new ArrayList<>();

            for(int i = 0; i < workTWeeks.length(); i++){
                JSONObject object = workTWeeks.getJSONObject(i);
                WlyyDoctorWorkWeek week = new WlyyDoctorWorkWeek();

                week.setDoctor(doctor);
                week.setDoctorName(doc.getName());
                week.setWeek(object.getString("week"));
                week.setMorning(object.getString("morning"));
                week.setAfternoon(object.getString("afternoon"));
                week.setNight(object.getString("night"));
                week.setCzrq(new Date());

                weeks.add(week);
            }

            doctorWorkWeekDao.save(weeks);
        }

        return true;
    }

    /**
     * 医生设置是否接受咨询
     *
     * @param doctor 医生
     * @param receiveConsult 是否接受咨询
     * @return
     */
    public boolean setDoctorReceiveConsult(String doctor,String receiveConsult) throws Exception {
        try {
            WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);

            // 未有设置，则新建医生设置
            if (workTime == null) {
                Doctor doc = doctorDao.findByCode(doctor);
                if (doc == null) {
                    throw new Exception("doctor can not find");
                }
                workTime = new WlyyDoctorWorkTime();
                workTime.setDoctor(doctor);
                workTime.setDoctorName(doc.getName());
            }

            // 设置是否接受咨询
            workTime.setReceiveConsult(receiveConsult);
            workTime.setCzrq(new Date());

            doctorWorkTimeDao.save(workTime);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 医生是否在工作
     *
     * @param doctor
     * @return
     */
    public JSONObject isDoctorWorking(String doctor){
        JSONObject json = new JSONObject();
        Calendar calendar = Calendar.getInstance();
        int week =  calendar.get(Calendar.DAY_OF_WEEK) - 1;

        if(week == 0){
            week = 7;
        }

        // 医生工作时间设置
        Map<String,Object> result = findDoctorWeekWork(doctor,String.valueOf(week));

        if(result.get("workTime") == null){
            // 医生未设置时，默认7*24小时工作
            json.put("status","1");
            json.put("msg","医生当前接受咨询");
        }else{
            WlyyDoctorWorkTime doctorWorkTime = (WlyyDoctorWorkTime)result.get("workTime");

            if(doctorWorkTime.getReceiveConsult().equals("0")){
                // 医生设置不接受咨询
                json.put("status","0");
                json.put("msg","医生不接受咨询");
            }else {
                if (result.get("workWeek") != null) {
                    // 当前工作日已设置工作时间
                    int flag = 0;
                    WlyyDoctorWorkTime workTime = (WlyyDoctorWorkTime) result.get("workTime");
                    WlyyDoctorWorkWeek workWeek = (WlyyDoctorWorkWeek) result.get("workWeek");
                    int hour = calendar.get(Calendar.HOUR_OF_DAY);
                    int minute = calendar.get(Calendar.MINUTE);
                    String current = (hour < 10 ? ("0" + hour) : hour) + ":" + (hour < 10 ? ("0" + minute) : minute);

                    // 早上
                    if (workWeek.getMorning().equals("1")) {
                        String currentStart = workTime.getMorningBegin();
                        String currentEnd = workTime.getMorningEnd();
                        if(currentStart.length() == 4){
                            currentStart = "0" + currentStart;
                        }
                        if(currentEnd.length() == 4){
                            currentEnd = "0" + currentEnd;
                        }
                        if (current.compareTo(currentStart) >= 0 &&
                                current.compareTo(currentEnd) < 0) {
                            flag = 1;
                        }
                    }
                    // 下午
                    if (workWeek.getAfternoon().equals("1")) {
                        String currentStart = workTime.getAfternoonBegin();
                        String currentEnd = workTime.getAfternoonEnd();
                        if(currentStart.length() == 4){
                            currentStart = "0" + currentStart;
                        }
                        if(currentEnd.length() == 4){
                            currentEnd = "0" + currentEnd;
                        }
                        if (current.compareTo(currentStart) >= 0 &&
                                current.compareTo(currentEnd) < 0) {
                            flag = 1;
                        }
                    }
                    //　晚上
                    if (workWeek.getNight().equals("1")) {
                        String currentStart = workTime.getNightBegin();
                        String currentEnd = workTime.getNightEnd();
                        if(currentStart.length() == 4){
                            currentStart = "0" + currentStart;
                        }
                        if(currentEnd.length() == 4){
                            currentEnd = "0" + currentEnd;
                        }
                        if (current.compareTo(currentStart) >= 0 &&
                                current.compareTo(currentEnd) < 0) {
                            flag = 1;
                        }
                    }

                    if(flag == 1){
                        json.put("status","1");
                        json.put("msg","医生当前接受咨询");
                    }else{
                        json.put("status","2");
                        json.put("msg","医生当前不在工作时间");
                    }
                }else{
                    json.put("status","2");
                    json.put("msg","医生当前不在工作时间");
                }
            }
        }

        return json;
    }
}
